﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Ellanet
{
    public partial class SampleForm : Form
    {
        readonly Timer _loseFocusTimer;
        IntPtr _hWndNewParent;

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        public SampleForm()
        {
            InitializeComponent();
            _loseFocusTimer = new Timer();
            _loseFocusTimer.Tick += loseFocusTimer_Tick;
            _loseFocusTimer.Interval = 250;
            _loseFocusTimer.Start();
            AttachToLogonUi(Handle);
        }

        void loseFocusTimer_Tick(object sender, EventArgs e)
        {
            _loseFocusTimer.Stop();

            if (IsLogonUIActive())
            {
                if (_hWndNewParent.ToInt32() != LogonUIHandle().ToInt32())
                {
                    AttachToLogonUi(Handle);
                }
            }

            _loseFocusTimer.Start();
        }

        void AttachToLogonUi(IntPtr childHwndf)
        {
            _hWndNewParent = FindWindow("AUTHUI.DLL: LogonUI Logon Window", null);
            SetParent(childHwndf, _hWndNewParent);
        }

        bool IsLogonUIActive()
        {
            return (FindWindow("AUTHUI.DLL: LogonUI Logon Window", null).ToInt32() != 0);
        }

        IntPtr LogonUIHandle()
        {
            return FindWindow("AUTHUI.DLL: LogonUI Logon Window", null);
        }
    }
}
